// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0

import { Logger } from "./logger.js";

// snippet-start:[javascript.v3.wkflw.topicsandqueues.logger]
export class SlowLogger extends Logger {
  constructor(delayInMs) {
    super();
    this.delay = delayInMs;
  }

  _sleep() {
    return new Promise((resolve) => setTimeout(resolve, this.delay));
  }

  /**
   * @param {string} message
   */
  async _logSlow(message) {
    const chars = message.split("");
    for (const c of chars) {
      process.stdout.write(c);
      await this._sleep();
    }
    process.stderr.write("\n");
  }

  /**
   * Write a message to the console. Split the message into multiple lines if
   * a line would be longer than the max width. Do not split in the middle of
   * a word.
   * - Generated by CodeWhisperer.
   * @param {string} message
   * @param {boolean} preformatted Ignore word wrapping if true. Default: false.
   * @param {number} maxWidth
   */
  async log(message, preformatted = false, maxWidth = 80) {
    const words = message.split(" ");
    let line = "";
    if (!preformatted) {
      for (const word of words) {
        if (line.length + word.length > maxWidth) {
          await this._logSlow(line);
          line = "";
        }
        line += word + " ";
      }
    }
    await this._logSlow(line);
  }
}
// snippet-end:[javascript.v3.wkflw.topicsandqueues.logger]
